
function formatDateTime (timeStamp, longflag = true) {
  var date = new Date();
  date.setTime(timeStamp * 1000);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  if (longflag == false) {
    return y + '-' + m + '-' + d;
  }
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
}

function formatDate(source, format) {
  if (!(source instanceof Date)) {
    source = parseDate(source)
  }
  const o = {
    'M+': source.getMonth() + 1,
    'd+': source.getDate(),
    'H+': source.getHours(),
    'm+': source.getMinutes(),
    's+': source.getSeconds(),
    'q+': Math.floor((source.getMonth() + 3) / 3),
    'f+': source.getMilliseconds()
  }
  if (/(y+)/.test(format)) {
    format = format.replace(RegExp.$1, (source.getFullYear() + '').substr(4 - RegExp.$1.length))
  }
  for (let k in o) {
    if (new RegExp('(' + k + ')').test(format)) {
      format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)))
    }
  }
  return format
}

function parseDate(dateStr) {
  if (typeof dateStr === 'string') {
    dateStr = dateStr.replace(/\-/g, '/')
  }
  return new Date(dateStr)
}

function dayAfter(target, offset = 0) {
  let now = parseDate(target)
  now.setDate(now.getDate() + offset)
  return now
}

function compare(x, y) {
  if (x < y) {
    return -1
  } else if (x > y) {
    return 1
  } else {
    return 0
  }
}

// 保留两位小数
function keepTwoDecimalFull(num) {
  let result = parseFloat(num)
  result = Math.round(result * 100) / 100
  let s_x = result.toString()
  let pos_decimal = s_x.indexOf('.')
  if (pos_decimal < 0) {
    pos_decimal = s_x.length
    s_x += '.'
  }
  while (s_x.length <= pos_decimal + 2) {
    s_x += '0'
  }
  return s_x
}

function isEmptyObject(e) {
  let t
  for (t in e)
    return !1
  return !0
}

function isPhoneAvailable(str) {
  var myreg = /^1[3456789]\d{9}$/
  if (!myreg.test(str)) {
    return false
  } else {
    return true
  }
}

var sumFlag = -1

function cutStringSum(chars) {
  chars = chars.replace(/[\ |\~|\`|\!|\@|\#|\$|\%|\^|\&|\*|\(|\)|\-|\_|\+|\=|\||\\|\[|\]|\{|\}|\;|\:|\"|\'|\,|\<|\.|\>|\/|\?]/g, "")
  chars = chars.replace(/[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/g, "")
  var sum = 0
  var charLen = chars.length
  for (var i = 0; i < charLen; i++) {
    var c = chars.charCodeAt(i)
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      sum++
    }
    else {
      sum += 2
    }
  }
  if (sum > 18) {
    chars = chars.substr(0, sumFlag)
  }
  else if (sum === 18) {
    sumFlag = charLen
  }
  else {
    sumFlag = -1
  }
  return chars
}

function getNodeRef(selector) {
  return new Promise((resolve, reject) => {
    try {
      wx.createSelectorQuery()
        .select(selector)
        .boundingClientRect(resolve)
        .exec()
    } catch (e) {
      console.error(e.message)
      reject(e.message)
    }
  })
}

function confirm(msg, confirmText = '确定', cancelText = '取消') {
  return new Promise(resolve => {
    wx.showModal({
      title: '',
      content: msg,
      confirmColor: '#a08257',
      confirmText: confirmText,
      cancelText: cancelText,
      success: function (res) {
        if (res.confirm) {
          resolve(true)
        } else {
          resolve(false)
        }
      }
    })
  })
}

function showAddressModal() {
  return confirm('请您添加收货地址').then(confirm => {
    if (confirm) {
      wx.navigateTo({
        url: '/pages/my/address/address'
      })
    }
  })
}

let toast = {}

toast.error = (msg, duration = 2000, image = '') => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      wx.showToast({
        title: typeof msg === 'object' ? JSON.stringify(msg) : msg,
        icon: 'none',
        image: image,
        duration: duration
      })
      setTimeout(resolve, duration)
    }, 100)
  })
}

toast.success = (msg, duration = 2000) => {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      wx.showToast({
        title: typeof msg === 'object' ? JSON.stringify(msg) : msg,
        duration: duration
      })
      setTimeout(resolve, duration)
    }, 100)
  })
}

function showLoading(title = '请稍候...', mask = true) {
  wx.showLoading({
    mask: mask,
    title: title
  })
}

function hideLoading() {
  wx.hideLoading()
}

module.exports = {
  formatDate,
  parseDate,
  dayAfter,
  compare,
  keepTwoDecimalFull,
  isEmptyObject,
  isPhoneAvailable,
  cutStringSum,
  getNodeRef,
  confirm,
  showAddressModal,
  toast,
  showLoading,
  hideLoading,
  formateDate: formatDate,
  formatDateTime: formatDateTime
}
